package cn.cdzdjd.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.PearVideoService;
import cn.cdzdjd.util.JsoupUtil;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class PearVideoServiceImpl implements PearVideoService {
	private final String baseUrl = "https://www.pearvideo.com/videoStatus.jsp?contId=";

	@Override
	public VideoInfoVO getVideoinfo(String url) {
		Document document = JsoupUtil.getDocument(url);
		Element ttbox = document.selectFirst("div[class=video-tt-box]");
		Element h1Element = ttbox.getElementsByTag("h1").first();
		String title = h1Element.text();
		String path = UrlUtil.getPath(url);
		int head = StringUtils.lastOrdinalIndexOf(path, "_", 1);
		String contId = StringUtils.substring(path, head + 1, path.length());
		Response res = JsoupUtil.getUrlResponse(baseUrl + contId);
		String jsonStr = res.body();
		JSONObject json = new JSONObject(jsonStr);
		if (json.getString("resultCode").equals("1")) {
			JSONObject videoInfo = json.getJSONObject("videoInfo");
			String poster = videoInfo.getString("video_image");
			String videoUrl = videoInfo.getJSONObject("videos").getString("srcUrl");
			// https://video.pearvideo.com/mp4/short/20240612/1718205944463-71107029-hd.mp4
			int index = StringUtils.lastOrdinalIndexOf(videoUrl, "/", 1);
			String videoName = StringUtils.substring(videoUrl, index);
			int flag = StringUtils.ordinalIndexOf(videoName, "-", 1);
			String videoNameTail = StringUtils.substring(videoName, flag);
			String videoNewName = "/cont-" + contId + videoNameTail;
			String videoHostPath = StringUtils.substring(videoUrl, 0, index);
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoHostPath + videoNewName));
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(poster));
			return new VideoInfoVO(videoList, posterList, title, null);
		} else {
			throw new RenException(ErrorCode.PARSE_ERROR, "解析失败");
		}
	}
}
